<?php

namespace Fluency\Web\Routing;

use Fluency\Web\Http\Request;

/**
 * A router that takes a list of other routers, queries them in the specified order and returns the
 * first non-null result (if possible).
 *
 * @package Fluency\Web\Routing
 * @author  Ignas Rudaitis
 * @since   1.0
 */
class ChainRouter implements Router
{
    private $routers;

    /**
     * The constructor.
     *
     * @param Fluency\Web\Routing\Router[] $routers the list of routers to query
     */
    public function __construct(array $routers)
    {
        $this->routers = $routers;
    }

    /**
     * @see Fluency\Web\Routing\Router::query()
     *
     * @param string $url
     * @return Fluency\Web\Http\Request|null
     */
    public function query($url)
    {
        foreach ($this->routers as $router) {
            $req = $router->query($url);
            if ($req !== null) {
                return $req;
            }
        }
    }
}
